package org.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

// Nacos 控制器类 用于接收心跳请求和注册服务   先注册 完了就心跳续杯即可
@RestController
@RequestMapping("/nacos")
public class MyNacosController {

    @Autowired
    private ServiceContext serviceContext;

    @Autowired
    private ListenerContext listenerContext;

    // 注册服务
    @PostMapping("/register")
    public ResponseEntity<String> registerService(@RequestBody ServiceInstance serviceInstance) {
        serviceContext.registerService(serviceInstance);

        listenerContext.notifyListeners(new ServiceChangeEvent(serviceInstance, ChangeType.LOGIN));
        return ResponseEntity.ok("Service registered successfully");
    }


    //  服务心跳  超时了则视为服务下线
    @PostMapping("/heartbeat")
    public ResponseEntity<String> heartbeat(@RequestBody ServiceInstance serviceInstance) {

        String serviceName = serviceInstance.getServiceName();

        Collection<ServiceInstance> services = serviceContext.getServices(serviceName);

        //不为空 找到服务实例 更新时间
        if (!services.isEmpty()) {
            for (ServiceInstance service : services) {
                if (service.equals(serviceInstance)) {
                    System.out.println("服务: " + serviceName + service.getIp() + ":" + service.getPort() + "心跳了");
                    // 更新心跳时间
                    service.setLastHeartbeat(System.currentTimeMillis());
                    return ResponseEntity.ok("Heartbeat received");
                }
            }
        }

        System.out.println("服务未找到 ：" + serviceInstance);

        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Service not found");
    }


    // 获取所有服务  返回map 他自己处理
    @GetMapping("/services")
    public Map<String,Collection< ServiceInstance>> getServices() {
        return serviceContext.getAllServices();
    }

    //获取所有监听者  仅测试用
    @GetMapping("/listeners")
    public Set<ServiceChangeListener> getListeners() {
        System.out.println("获取所有监听者");
        return listenerContext.getListeners();
    }


    //注册监听器  顺便回给他服务列表
    @PostMapping("/registerListener")
    public Map<String,Collection< ServiceInstance>>  registerListener(@RequestParam("ip") String ip, @RequestParam("port") Integer port) {
        //打印参数
        System.out.println("注册监听器: " + ip + " : " + port);
        ServiceChangeListener listener = new ServiceChangeListener(ip, port);
        System.out.println("有服务注册了监听器: " + listener.getIp() + " : " + listener.getPort());
        listenerContext.addListener(listener);
        return getServices();
    }


}
